'use strict';

const Service = require('egg').Service;
const md5 = require('md5')
const path = require('path');
const sendToWormhole = require('stream-wormhole');
const mongoose = require('mongoose');
class NormalService extends Service{
    async upfile(type,url){
        const {ctx} = this;
        const parts = await ctx.multipart();
        let part;
        while ((part = await parts()) != null) {
            if (part.length) {
              
            } else {
                if (!part.filename) {
                    // user click `upload` before choose a file,
                    // `part` will be file stream, but `part.filename` is empty
                    // must handler this, such as log error.
                    return;
                }
      
                let result;
                try {
                    let str = md5(new Date().getTime());
                    if(type!='img'){
                        str= part.filename;
                    }else{
                        str = part.filename.indexOf('png')>0?(str+'.png'):str+'.jpg';
                    }
                    result = await ctx.oss.put(url+'/' + str, part);
                    return result;
                } catch (err) {
                    await sendToWormhole(part);
                    throw err;
                }
               
            }
        }
    }
    async isresult(result){
        const {ctx} = this;
        if(result==null){
            ctx.status = 404;
            ctx.body = {data:0,content:'参数错误'};
            return null;
        }
    }
    async addinfo(models,data){
        const {ctx} = this;
        try {
            let res = await ctx.model[models].insertMany(data);
            return {data:1,content:'信息添加成功',id:res[0]._id};
        } catch (error) {
            console.log(error)
            return {data:0,content:error};
        }
    }
    async statebyjson(models,json,states){
        const {ctx} = this;
        if(!json){
            ctx.status = 404;
            ctx.body = {data:0,content:'参数错误'};
            return null;
        }
        try {
            let res = await ctx.model[models].updateMany(json,{$set:states});
            return {data:1,content:'信息修改成功'};
        } catch (error) {
            console.log(error)
            return {data:0,content:error};
        }
    }
    async statebyid(models,id,states){
        try {
            const {ctx} = this;
            if(!id){
                ctx.status = 404;
                ctx.body = {data:0,content:'参数错误'};
                return null;
            }
            let res = await ctx.model[models].update({ _id: mongoose.mongo.ObjectId(id) },{$set:states});
            return {data:1,content:'信息修改成功'};
        } catch (error) {
            console.log(error)
            return {data:0,content:error};
        }
    }
    async updateinfobyid(models,id,json){
        const {ctx} = this;
        if(!id){
            ctx.status = 404;
            ctx.body = {data:0,content:'参数错误'};
            return null;
        }
        try {
            let res = await ctx.model[models].update({ _id: mongoose.mongo.ObjectId(id) },json);
            return {data:1,content:'信息修改成功'};
        } catch (error) {
            return {data:0,content:error};
        }
    }
    async getinfobyid(models,id){
        const {ctx} = this;
        if(!id){
            ctx.status = 404;
            ctx.body = {data:0,content:'参数错误'};
            return null;
        }
        try {
            let result = await ctx.model[models].findOne({ _id: mongoose.mongo.ObjectId(id) });
            return {data:1,result};
        } catch (error) {
            return {data:0,content:error};
        }
    }
    async getinfo(models,obj){
        const {ctx} = this;
        if(!obj){
          return {data:0,content:'参数错误'};
        }
        try {
            let result = await ctx.model[models].findOne(obj);
            return {data:1,result};
        } catch (error) {
            return {data:0,content:error};
        }
    }
    async getinfos(model,json,page,size,sorts=null){
       const {ctx} = this;
       try {
            page =parseInt(page);
            size = parseInt(size);
            let info = {};
            for(let [key,value] of Object.entries(json)){
                if(value!=null)info[key]=value;
            }
            let sort = { create_at: -1 };
            if(sorts!=null) sort = sorts;
            let total = await ctx.model[model].count(info); 
            let result = await ctx.model[model].find(info).sort(sort).limit(size).skip((page - 1) * size);
            return {data:1,result:{total,result}};
       } catch (error) {
           console.log(error)
            return {data:0,content:error};
       }
    }
    async getlimits(model,state,limit=null){
        try {
            const {ctx} = this;
            let result;
            if(limit==null){
                result = await ctx.model[model].find(state);
            }else{
                result = await ctx.model[model].find(state).limit(limit);
            }
            return {data:1,result};
        } catch (error) {
            return {data:0,content:error};
        }
    }

    async remTable(models,id){
        const {ctx} = this;
        try {
            let res = await ctx.model[models].remove({_id: mongoose.mongo.ObjectId(id)});
            return {data:1,content:'信息删除成功'};
        } catch (error) {
            console.log(error)
            return {data:0,content:error};
        }
    }

    async remTabless(models,json){
        const {ctx} = this;
        try {
            let res = await ctx.model[models].deleteMany(json);
            return {data:1,content:'信息删除成功'};
        } catch (error) {
            console.log(error)
            return {data:0,content:error};
        }
    }

}
module.exports = NormalService;